/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Administrator
 * Date: 2023-09-10
 * Time: 8:44
 */
public class Test {

    public ListNode detectCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        while (true) {
            if (fast == null || fast.next == null){
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow){
                break;
            }
        }

        fast = head;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;


        public ListNode deleteDuplication(ListNode pHead) {
        ListNode cur = pHead;
        ListNode slow = pHead;
        ListNode fast = cur.next;

        while(fast != null && fast.next != null){
            if(slow.val == fast.val){
                slow.next = fast.next;
                fast = fast.next;
            }else{
                slow = slow.next;
                if(fast.next != null){
                    fast = fast.next;
                }
            }
        }
        return cur;
    }
    public ListNode oddEvenList(ListNode head) {
        if(head == null){
            return head;
        }
        ListNode cur = head.next;
        ListNode slow = head;
        ListNode fast = cur;
        while(fast != null && fast.next != null){
            slow.next = fast.next;
            slow = slow.next;
            fast.next = slow.next;
            fast = fast.next;
        }
        slow.next = cur;
        return head;
    }
    public ListNode sortList(ListNode head) {
        return mergeSort(head);
    }
    public ListNode findMid(ListNode head) {
        if (head==null) return head;

        ListNode fast = head.next;  // 快指针 每次走2步
        ListNode slow = head;       // 慢指针 每次走1步
        while (fast!=null && fast.next!=null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

    public ListNode mergeSort(ListNode head) {
        if (head==null || head.next==null) {
            return head;
        }
        ListNode mid = findMid(head);
        ListNode next = mid.next;
        mid.next = null;
        ListNode left = mergeSort(head);
        ListNode right = mergeSort(next);
        return merge(left, right);
    }

    public ListNode merge(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode curr = dummy;
        while (l1!=null && l2!=null) {
            if (l1.val<l2.val) {
                curr.next = l1;
                l1 = l1.next;
            } else {
                curr.next = l2;
                l2 = l2.next;
            }
            curr = curr.next;
        }

        if (l1!=null) {
            curr.next = l1;
        }

        if (l2!=null) {
            curr.next = l2;
        }
        return dummy.next;
    }
    public static void main(String[] args) {

    }
}
